<template>
	<div class="container">
		<svg :width="svgWidth" :height="svgHeight" :viewBox="`0 0 ${svgWidth} ${svgHeight}`">
			<!-- 点位显示 -->
			<g v-for="(point, index) in points" :key="index" @click="selectPoint(point)" class="point-group">
				<!-- 呼吸效果背景 -->
				<circle :cx="point.x" :cy="point.y" r="15" class="point-circle"
					:class="{ 'start-point': isStartPoint(point), 'end-point': isEndPoint(point) }" />
				<!-- 图标 -->
				<image :x="point.x - 10" :y="point.y - 10" :width="20" :height="20"
					:xlink:href="getIconPath(point.pointType)" class="point-icon" />
				<!-- 文本标签 -->
				<text :x="point.x + 15" :y="point.y - 15" class="point-label">
					{{ point.pointName }}
				</text>
			</g>
		</svg>
		<!-- 选中点位信息展示 -->
		<div v-if="selectedPoint" class="info-card" :style="{ left: pos.x + 'px', top: pos.y + 'px' }">
			<div class="header" @mousedown="startDrag">
				<h3>点位详细信息 (拖动我)</h3>
			</div>
			<div class="content">
				<!-- 当前选中信息 -->
				<section class="current-point">
					<h4>当前点位</h4>
					<p>ID: {{ selectedPoint.id }}</p>
					<p>名称: {{ selectedPoint.pointName }}</p>
					<!-- 已选信息 -->
					<section class="selected-info" v-if="linePoint.length">
						<template v-for="(item,index) in linePoint">
							<div class="selected-item" >
								<template v-if="item.start">
									<el-tag type="success" size="small">起点</el-tag>
								</template>
								<template v-else-if="item.end">
									<el-tag type="danger" size="small">终点</el-tag>
								</template>
								<template v-else>
									<el-tag  size="small">经停点</el-tag>
								</template>
								<span>{{ item.pointName }}</span>
							</div>
						</template>
					</section>
					<!-- 操作按钮 -->
					<div class="action-buttons">
						<el-button plain @click="handleAutoSaveLine">
							自动规划路线
						</el-button>
						<el-button plain @click="handleSaveLine">
							手动规划路线
						</el-button>
					</div>
					<!-- 操作按钮 -->
					<template v-if="isPlanRoute">

						<div class="action-buttons" v-if="autoSaveLine">
							<el-button type="success" plain @click="setAsStart">
								<template #icon>
									<Location />
								</template>
								设为起点
							</el-button>
							<el-button type="danger" plain @click="setAsEnd">
								<template #icon>
									<Place />
								</template>
								设为终点
							</el-button>
						</div>
						<div class="action-buttons" v-else>
							<el-button type="success" plain @click="setAsStart">
								<template #icon>
									<Location />
								</template>
								设为起点
							</el-button>
							<el-button  plain @click="setLinePoint">
								设置经停点
							</el-button>
							<el-button type="danger" plain @click="setAsEnd">
								<template #icon>
									<Place />
								</template>
								设为终点
							</el-button>
						</div>
					</template>

				</section>
				<div class="action-group">
					<el-button type="primary" :disabled="isLoading"
						:class="{ 'highlight-button': (linePoint.length  === 2 && autoSaveLine) ||  (linePoint.length  >  2 )}" @click="handlePathPlanning">
						{{ isLoading ? '规划中...' : '开始路径规划' }}
					</el-button>
					<el-button  type="danger" @click="handleClosePlan" class="cancel-button">
						关闭页面
					</el-button>
					<el-button v-if="startPoint || endPoint" type="info" @click="clearPoints" plain>
						清空起终点
					</el-button>
					<el-button v-if="isLoading" type="danger" @click="cancelPathPlanning" class="cancel-button">
						取消规划
					</el-button>
				</div>
			</div>
		</div>
	</div>
</template>
<script setup>
import {
	ref,
	reactive,
	onMounted,
	computed,
	onUnmounted
} from 'vue';
import {
	ElMessage
} from 'element-plus';
import {
	wcao,
	post,
	rgvpost
} from "@/http";
import axios from 'axios';
import './css/zhi0225.css';
import {
	Location,
	Place
} from '@element-plus/icons-vue';
import http from '../../../utils/http';
import { isEqual } from "lodash";

// 导入图片（将你的图片放在public/icons目录下）
const iconMap = {
	'CAR': '/icons/car.svg',
	'WAREHOUSE': '/icons/ku.svg',
	'TRANSFER': '/icons/zhuan.svg',
	'DEFAULT': '/icons/default.svg'
};
// 新增图标获取方法
const getIconPath = (type) => {
	return iconMap[type] || iconMap.DEFAULT;
};
const linePoint = ref([]);
const isPlanRoute = ref(false);
const autoSaveLine = ref(false);
// SVG画布尺寸
const svgWidth = ref(window.innerWidth);
const svgHeight = ref(window.innerHeight);
const points = ref([]);
const selectedPoint = ref(null);
const startPoint = ref(null);
const endPoint = ref(null);
const pathPoints = ref([]);
const isLoading = ref(false);
const abortController = ref(null);
// 新增拖动相关状态
const pos = ref({
	x: 20,
	y: 20
});
const dragging = ref(false);
const startX = ref(0);
const startY = ref(0);
const initialPos = ref({
	x: 0,
	y: 0
});

//手动规划路线
const handleSaveLine = () => {
	autoSaveLine.value = false
	startPlanRoute()
}

//自动规划路线
const handleAutoSaveLine = () => {
	autoSaveLine.value = true
	startPlanRoute()
}

//设置开始规划路线
const startPlanRoute = () => {
	linePoint.value = []
	isPlanRoute.value = true
}

// 计算属性
const isCurrentStart = computed(() =>
	selectedPoint.value?.id === startPoint.value?.id
)

const isCurrentEnd = computed(() =>
	selectedPoint.value?.id === endPoint.value?.id
)
// 方法
const isStartPoint = (point) =>
	point.id === startPoint.value?.id

const isEndPoint = (point) =>
	point.id === endPoint.value?.id
// 窗口尺寸处理
const handleResize = () => {
	svgWidth.value = window.innerWidth;
	svgHeight.value = window.innerHeight;
};
const startDrag = (e) => {
	dragging.value = true;
	startX.value = e.clientX;
	startY.value = e.clientY;
	initialPos.value = {
		...pos.value
	};

	// 添加全局事件监听
	document.addEventListener('mousemove', onDrag);
	document.addEventListener('mouseup', stopDrag);
};
const onDrag = (e) => {
	if (!dragging.value) return;

	const dx = e.clientX - startX.value;
	const dy = e.clientY - startY.value;

	pos.value = {
		x: initialPos.value.x + dx,
		y: initialPos.value.y + dy
	};
};

const stopDrag = () => {
	dragging.value = false;
	document.removeEventListener('mousemove', onDrag);
	document.removeEventListener('mouseup', stopDrag);
};
// 点位选择处理
const selectPoint = (point) => {
	console.log(point, "point");
	selectedPoint.value = selectedPoint.value?.id === point.id ?
		null :
		point;
};
// 添加resize监听
onMounted(() => {
	window.addEventListener('resize', handleResize);
});

// 移除监听
onUnmounted(() => {
	window.removeEventListener('resize', handleResize);
});
// 判断特殊点位
const isSpecialPoint = (point) => {
	return point.id === startPoint.value?.id ||
		point.id === endPoint.value?.id;
};

// 设置起点终点
const setAsStart = () => {
	linePoint.value[0] = {
		...selectedPoint.value,
		start:true
	} 
	ElMessage.success(`已设置起点：${selectedPoint.value.pointName}`);
};

//设置经停点
const setLinePoint = ()=>{
	const point = linePoint.value[linePoint.value.length - 1];
	if(point.end){
		ElMessage.error(`已经设置终点，不能继续增加经停点`);
		return
	}
	linePoint.value.push({
		...selectedPoint.value
	})
}

const setAsEnd = () => {
	const length = linePoint.value.length;
	if(length  === 0){
		ElMessage.error(`请先设置起点`);
	}
	const point = { ...linePoint.value[linePoint.value.length - 1]};
	if(isEqual({...point},{...selectedPoint.value,start:true})){
		ElMessage.error(`不能将起点设置为终点`);
		return 
	}
	const endPoint = {
		...selectedPoint.value,
			end:true
	}
	if(autoSaveLine.value){
		linePoint.value[1] = endPoint
		return
	}
	if(!point.end && !isEqual(point,selectedPoint.value)){
		linePoint.value.push(endPoint);
		return 
	}
	linePoint.value[linePoint.value.length - 1] = {
		...selectedPoint.value,
		end:true
	}
};
// 路径规划处理
const handlePathPlanning = async () => {
	isLoading.value = true;
	console.log(linePoint.value);
	return
	const res = await http.post('/device/dispatch', {
		start: startPoint.value,
		end: endPoint.value
	});
	console.log(res)
	// pathPoints.value = response.data.map(p => ({
	// 	x: Number(p.locationX),
	// 	y: Number(p.locationY)
	// }));
	// ElMessage.success('路径规划成功');
	// isLoading.value = false;
};
// 更新路径计算
const pathData = computed(() => {
	if (pathPoints.value.length === 0) return '';
	return pathPoints.value
		.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`)
		.join(' ');
});
// 清空起终点
const clearPoints = () => {
	linePoint.value = [];
	ElMessage.info('已清空起终点');
};

// 取消路径规划
const cancelPathPlanning = () => {
	if (abortController.value) {
		abortController.value.abort();
		ElMessage.warning('已取消路径规划');
	}
	isLoading.value = false;
	linePoint.value = [];
};

//关闭规划页面
const handleClosePlan = ()=>{
	resetDialog()
}

//重置弹窗数据
const resetDialog = ()=>{
	linePoint.value = [];
	isPlanRoute.value = false;
	isLoading.value = false;
	selectedPoint.value = null;
}

// 修改模拟数据生成（添加pointType）
const generateMockData = () => {
	return [{
		id: 1,
		x: 100,
		y: 100,
		pointType: 'CAR',
		pointName: '车辆点位'
	},
	{
		id: 2,
		x: 200,
		y: 150,
		pointType: 'WAREHOUSE',
		pointName: '仓库点位'
	},
	{
		id: 3,
		x: 300,
		y: 300,
		pointType: 'TRANSFER',
		pointName: '转折点位'
	}
	];
};

// 路径生成计算属性
const loadpathData = computed(() => {
	if (points.value.length === 0) return '';
	return points.value
		.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p.x} ${p.y}`)
		.join(' ');
});

const fetchPoints = async () => {
	let res = await http.post('/points/getAll'); // 替换为实际的 API 地址
	if (!Array.isArray(res)) {
		console.error(`无效的响应类型，预期数组，实际得到: ${typeof res}`);
		return
	}
	// 数据转换
	let validPoints = res
		.map(p => ({
			id: Number(p.id),
			pointName: p.pointName || '未命名',
			pointType: p.pointType || 'DEFAULT',
			x: Number(p.locationX) || 0,
			y: Number(p.locationY) || 0,
			nodeId: p.nodeId
		}))
		.filter(p => Number.isInteger(p.id) && p.id > 0);
	// 更新状态
	points.value = validPoints;
};
// 组件挂载时获取初始数据
onMounted(() => {
	document.title = '调度服务页面';
	fetchPoints()
})
// 组件卸载时取消请求
onUnmounted(() => {
	if (abortController.value) {
		abortController.value.abort();
	}
});
</script>

<style scoped></style>